#! /usr/bin/python
# -*- coding: utf-8 -*-

import hashlib
import time
import conf

def md5(str):
    h = hashlib.md5()
    h.update(str)
    return h.hexdigest()

def signature(paramsDict, secret):
    sortedKeysList = paramsDict.keys()
    sortedKeysList.sort()
    sigStr = ''
    for key in sortedKeysList:
        value = paramsDict[key]
        if not value:
            return False
        sigStr += key + '=' + value
    sigStr += secret
    sig = md5(sigStr)
    return sig

def getXnCookieDict(cookies):
    xnuid = cookies.get(conf.api_key + '_user')
    sessionKey = cookies.get(conf.api_key + '_session_key')
    ss = cookies.get(conf.api_key + '_ss')
    expires = cookies.get(conf.api_key + '_expires')
    sig = cookies.get(conf.api_key)
    cookieDict = {
        'user': xnuid,
        'session_key': sessionKey,
        'ss': ss,
        'expires': expires,
        'sig': sig
    }
    return cookieDict

def validateXnCookies(cookieDict, appSecret):
    expires = cookieDict.get('expires')
    if not expires:
        return False
    try:
        expires = int(expires)
    except ValueError:
        return False
    currentTime = int(time.time())
    if expires < currentTime:
        return False
    expectedSig = cookieDict.get('sig')
    if not expectedSig:
        return False
    del cookieDict['sig']
    sig = signature(cookieDict, appSecret)
    if sig != expectedSig:
        return False
    return True

def getUrlPathQuery(request):
    path = request.path
    if request.query_string:
        path += '?' + request.query_string
    return path

def getCategoryByNav(nav):
    catValue = 'all'
    for category in conf.paperCategoryList:
        if nav == category.get('nav'):
            return category.get('catValue')
    return catValue
def getCategoryTextByValue(catValue):
    catText = '其它'
    for category in conf.paperCategoryList:
        if catValue == category.get('catValue'):
            return category.get('catText')
    return catText
def getCategoryNavByValue(catValue):
    nav = '其它'
    for category in conf.paperCategoryList:
        if catValue == category.get('catValue'):
            return category.get('nav')
    return nav

#'&' ==> '&amp;'
#'<' ==> '&lt;'
#'>' ==> '&gt;'
#'"' ==> '&quot;'
def htmlEncode(unencoded):
    #encoded = unencoded.replace('&','&amp;').replace('<','&lt;').replace('>','&gt;').replace('"','&quot;')
    #the above replace-based encoding method has low effiency!
    encodingMap = {
        '&':'&amp;',
        '<':'&lt;',
        '>':'&gt;',
        '"':'&quot;'
    }
    encodedList = []
    lasti = 0
    i = 0
    lenEncoded = len(unencoded)
    while i < lenEncoded:
        char = unencoded[i]
        #in fact, char is a string in python
        if char == '&' or char == '<' or char == '>' or char == '"':
            encodedList.append(unencoded[lasti:i])
            encodedList.append(encodingMap[char])
            lasti = i + 1
        i += 1
    if lasti < lenEncoded:
        encodedList.append(unencoded[lasti:i])
    #concat encodedList to a string
    encoded = ''
    for subEncoded in encodedList:
        encoded += subEncoded
    return encoded

#Transform UTC time (of type datetime.datetime) to Local time
def calculateLocalTime(UTCDataTime):
    localTime = '%04d-%02d-%02d %02d:%02d' % (
        UTCDataTime.year, 
        UTCDataTime.month, 
        UTCDataTime.day, 
        (UTCDataTime.hour + 8) % 24, 
        UTCDataTime.minute)
    return localTime
